package org.amphiprion.kidcalendar.tool;

import java.util.Date;
import java.util.List;

import org.amphiprion.kidcalendar.entity.Period;
import org.amphiprion.kidcalendar.entity.Rule;
import org.amphiprion.kidcalendar.entity.VacationRule;

public class RuleEvaluator {
	public enum RuleFilter {
		ANY_RULE, ONLY_VACATION_RULE, EXCLUDE_VACATION_RULE
	}

	public static Period evaluate(Date date, List<Rule> rules) {
		return evaluate(date, rules, RuleFilter.ANY_RULE);
	}

	public static Period evaluate(Date date, List<Rule> rules, RuleFilter ruleFilter) {

		Period period = null;
		for (Rule rule : rules) {
			if (ruleFilter == RuleFilter.EXCLUDE_VACATION_RULE && rule instanceof VacationRule) {
				continue;
			}
			if (ruleFilter == RuleFilter.ONLY_VACATION_RULE && !(rule instanceof VacationRule) && rule.getSubRules().size() == 0) {
				continue;
			}
			Period pResult = rule.verifyDate(date);
			if (pResult != null) {
				if (rule.getSubRules().size() > 0) {
					period = evaluate(date, rule.getSubRules(), ruleFilter);
				} else {
					period = pResult;
				}
				if (period != null) {
					return period;
				}
			}
		}
		return null;
	}
}
